package cn.zhz.cloud.token.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import cn.zhz.cloud.token.dto.CurrentUserDto;
import cn.zhz.cloud.token.exception.TokenException;
import cn.zhz.cloud.token.util.CurrentUserContextHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static cn.zhz.cloud.token.constant.TokenConstant.HEADER_USER;
import static cn.zhz.cloud.token.constant.TokenConstant.TOKEN_AES_CRYPTO_KEY_BYTE;

@Slf4j
public class HandlerTokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userToken = request.getHeader(HEADER_USER);
        if (StrUtil.isBlank(userToken)) {
            throw new TokenException(String.format("请求路径：%s,令牌为空", request.getRequestURI()));
        }
        String userDecryptStr = SecureUtil.aes(TOKEN_AES_CRYPTO_KEY_BYTE).decryptStr(userToken);
        log.debug("解析的用户信息为:{}", userDecryptStr);

        if (!JSONUtil.isTypeJSON(userDecryptStr)) {
            throw new TokenException("令牌格式错误");
        }

        CurrentUserContextHandler.setUser(JSONUtil.toBean(userDecryptStr, CurrentUserDto.class));
        CurrentUserContextHandler.setUserToken(userToken);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUserContextHandler.clear();
    }
}
